import java.util.concurrent.PriorityBlockingQueue;

public class work1 {
    public class MyTimer {
        //定义线程内容
        private PriorityBlockingQueue<Mytask> priorityBlockingQueue=new PriorityBlockingQueue<>();

        public MyTimer() {
            //扫描线程
            Thread th1 = new Thread (()-> {
                synchronized (this) {
                    while (true) {
                        try {
                            Mytask take = priorityBlockingQueue.take();
                            //判断有没有到时间
                            long times = System.currentTimeMillis();
                            if (times >= take.getTime()) {
                                //时间到了执行任务
                                take.getRunnable().run();
                            } else {
                                long waittime = take.getTime() - times;
                                //没有到时间放回阻塞队列
                                priorityBlockingQueue.put(take);
                                //进行休眠
                                this.wait(waittime);
                            }
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            });
            th1.start();
        }
        public void schedule(Runnable runnable,long time) {
            //构建一个Mytask对象
            Mytask mytask=new Mytask(runnable,time);
            //放入阻塞数组
            priorityBlockingQueue.put(mytask);
            //唤醒等待线程
            synchronized (this){
                this.notifyAll();
            }
        }

    }

}
